package com.fatan.xiaopacai.mvvm.viewmodel

import android.util.Log
import androidx.compose.runtime.MutableIntState
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import com.fatan.xiaopacai.base.BaseViewModel
import com.fatan.xiaopacai.base.TAG
import com.fatan.xiaopacai.mvvm.model.maxShaiZiNum
import com.fatan.xiaopacai.mvvm.model.minShaiZiNum
import com.fatan.xiaopacai.room.AppDataBase
import com.fatan.xiaopacai.room.randomshaizi.RandomShaiZiEntity
import com.fatan.xiaopacai.util.JsonUtil
import kotlin.random.Random

/**
 * @author: WangYeTong
 * @date: 2023/12/26 18:09
 * @remake:
 */
class RandomShaiZiViewModel : BaseViewModel() {
    private val _shaiZiNum = mutableIntStateOf(5)
    val shaiZiNum: MutableIntState
        get() = _shaiZiNum

    private val _randomDataList = mutableStateOf<List<Int>>(listOf())
    val randomDataList: MutableState<List<Int>>
        get() = _randomDataList

    fun shaiZiAdd() {
        if (_shaiZiNum.intValue < maxShaiZiNum) {
            _shaiZiNum.intValue++
        }
    }

    fun shaiZiMinus() {
        if (_shaiZiNum.intValue > minShaiZiNum) {
            _shaiZiNum.intValue--
        }
    }

    /**
     * 获取随机数集合
     */
    fun getRandomDataList() {
        _randomDataList.value = mutableListOf<Int>().apply {
            for (index in 0 until shaiZiNum.intValue) {
                add(Random.nextInt(1, 7))
            }
        }
    }

    /**
     * 添加到数据库
     */
    fun addRecord(data: List<Int>) = serverAwait {
        Log.i(TAG, "随机摇骰子添加记录:${JsonUtil.toJson(data)}")
        AppDataBase.database.randomShaiZiDao().insertAll(RandomShaiZiEntity(shaiZiList = data, timeMill = System.currentTimeMillis()))
    }
}